import React, { useState,useEffect } from 'react'
import { Editor } from "react-draft-wysiwyg";
// 导入处理draft文本流的方法
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs'
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
// 该文件是为了兼容draftjs报错的问题********重要********不可删除********
import {myBlockRenderer} from './customBlockRenderFunc.js'

export default function ArticleEditor(props) {
    const [editorState, setEditorState] = useState('')
    useEffect(()=>{
        // html-===> draft,把html转换为draft类型
        const html = props.content
        // 防止新增时触发转换报错，如果是新增就直接return
        if(html===undefined) return 
        const contentBlock = htmlToDraft(html);
        if (contentBlock) {
          const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const editorState = EditorState.createWithContent(contentState);
            // 把转换完的数据设置给状态，这样受控的富文本编辑器就可以显示文本了
          setEditorState(editorState)
        }
    },[props.content])
    return (
        <div>
            <Editor
                // 这两个属性是让改组件变成受控组件，一定要配合使用
                editorState={editorState}
                onEditorStateChange={(e) => {
                    setEditorState(e)
                }}
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName="editorClassName"
                customBlockRenderFunc={myBlockRenderer}
                // 失去焦点时操作
                onBlur={() => {
                    // 通过draft的处理函数把富文本数据进行处理转换为html
                    // 并传递给父组件
                    props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
                }}
            />
        </div>
    )
}
